class ItemCategory < ActiveRecord::Base
	set_primary_key "t_cid"
  has_many :children, :class_name => "ItemCategory", :foreign_key => "parent_id",:order => "sort_order ASC", :conditions => ["status = ?", 1]
  belongs_to :parent, :class_name => "ItemCategory", :foreign_key => "parent_id"
  
  OUTPUT_HASH = {:include =>:children}
  ALL_OUTPUT_HASH = {:include =>{:children=>{:include=>:children}}}
  
	named_scope :period, lambda { |*params| {:conditions => ["parent_id = ? and status = ? ", params[0], params[1]], :order => 'sort_order ASC'}}
	named_scope :cat1, :conditions => ["cat_level = ? AND status = ?",0,1],:order => 'sort_order ASC'
  named_scope :cat2, :conditions => ["cat_level = ? AND status = ?",1,1],:order => 'sort_order ASC'
  named_scope :cat3, :conditions => ["cat_level = ? AND status = ?",2,1],:order => 'sort_order ASC'
  
  named_scope :lists, lambda {|channel_id,limit| {:select=>'t_cid,t_cat_name,sort_order',:limit=>limit,:conditions => ["parent_id = ?", channel_id],:order=>'sort_order'}}
  named_scope :sublists, lambda {|list_id| {:conditions => ["parent_id = ?", list_id],:order=>'sort_order'}}
    
  def self.get_sublists(list_id)
    cat_id_name_hash = {}
    ItemCategory.lists(list_id).each {|category|
      cat_id_name_hash[category.id] = category.cat_name
    }
    cat_id_name_hash
  end
  
	## admin ##
	def custom_delete
    self.update_attribute("status", 0)
    return if self.cat_level == 2

    self.children.each{|child|child.custom_delete}
    #self.delete_cat_products
  end
  
  def delete_cat_products
    case self.cat_level
    when 1
      Product.find_all_by_cat1_id(self.id).each{|prod|prod.custom_delete_with_cat}
    when 2
      Product.find_all_by_cat2_id(self.id).each{|prod|prod.custom_delete_with_cat}
    when 3
      Product.find_all_by_cat3_id(self.id).each{|prod|prod.custom_delete_with_cat}
    end
  end
  
end
